<template>
<div v-if="addVisible" class="subeditpanelPop">
  <div class="editpanel  twoStageWindow" style="padding-bottom:0;">
    <div class="twoStageWindowTitle" v-if = "subModel == 'myEntry'">
      数据录入
      <div class="twoStageWindowClose" >
        <el-button size="mini" type="primary" v-on:click="resultentry('commit',false)" :disabled="!isRepeat">提交</el-button>

        <el-button size="mini" type="primary" v-on:click="resultentry('save',false)" :disabled="!isRepeat">保存</el-button>
        <el-button size="mini" v-on:click="close">取消</el-button>
      </div>
    </div>
    <div class="twoStageWindowTitle" v-if = "subModel == 'myCheck'">
      数据校核
      <div class="twoStageWindowClose" >
        <el-button size="mini" type="primary" v-on:click="doPass" :disabled="!isRepeat">校核</el-button>
        <el-button size="mini" v-on:click="close">取消</el-button>
      </div>
    </div>
    <div class="twoStageWindowTitle" v-if = "subModel == 'myReview'">
      数据审核
      <div class="twoStageWindowClose" >
        <el-button size="mini" type="primary" v-on:click="doPass" :disabled="!isRepeat"  v-if = "$parent.subIsEdit != 'look'" >审核</el-button>
        <el-button size="mini" v-on:click="close">取消</el-button>
      </div>
    </div>
    <div class="twoStageWindowTitle" v-if = "subModel == 'myReviewUpdate'">
      数据修改
      <div class="twoStageWindowClose" >

        <el-button size="mini" type="primary" v-on:click="resultentry('commit',false)" :disabled="!isRepeat">提交</el-button>
        <el-button size="mini" v-on:click="close">取消</el-button>
      </div>
    </div>
    <div class="containercontent" style="margin-top: 40px;height:calc(100% - 40px);padding:0 20px;">
      <div>
        <div style="height:35px;line-height:35px;">
            检测单信息
        </div>
        <div id="aSinglBatch">
          <el-table :data="testEntryDetail" size="mini" style="width:100%;">
            <el-table-column prop="code" label="检测单号" show-overflow-tooltip  min-width="80px"></el-table-column>
            <el-table-column prop="checkerName" label="校核人员" show-overflow-tooltip  min-width="80px">
            </el-table-column>
            <el-table-column prop="togetherWithName" label="共同完成人"  min-width="80px"></el-table-column>
            <el-table-column prop="status" label="状态" :formatter="formatterStatus"  min-width="80px"></el-table-column>
            <el-table-column prop="desc" label="备注" v-if = "subModel != 'myEntry'"></el-table-column>
            <el-table-column prop="desc" label="备注" v-if = "subModel == 'myEntry'">
              <template slot-scope="scope">
                  <el-input size="mini" v-model="subTestpanelData.desc"></el-input>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      <div style="padding:20px 0;height:calc(100% - 105px)">
        <div style="padding-bottom: 10px;height:100%;" class = "elTab">
              <el-tabs v-model="activeName" >
                <el-tab-pane label="检测项目" name="first">
                  <div  style = "float:right;wdth:100px;margin-bottom:10px" v-if = "subModel == 'myEntry'">
                    <el-button size="mini" type="primary" @click="excelTemplet">导出模板</el-button>
                    <form id="fileForm1" style="display:inline-block">
                      <input type="file" name="file" id="file1" @change="upload1">
                    </form>
                    <el-button size="mini" type="primary" @click="uploadClick1">导入结果</el-button>
                  </div>

                  <el-table :data="subTestpanelData.subItems" size="mini" style="width:100%;height:calc(100% - 38px);" class = "tableCon">
                    <el-table-column label="序号" min-width="50px">
                      <template slot-scope="scope">
                        {{scope.$index+1}}
                      </template>
                    </el-table-column>
                    <el-table-column prop="taskName" label="任务名称" show-overflow-tooltip  min-width="100px">
                    </el-table-column>
                    <el-table-column prop="sampleName" label="样品名称"  show-overflow-tooltip  min-width="100px"></el-table-column>
                    <el-table-column prop="sampleCode" label="样品编码"  show-overflow-tooltip  min-width="100px"></el-table-column>
                    <el-table-column prop="methodName" label="检测方法"  show-overflow-tooltip  min-width="100px"></el-table-column>

                    <el-table-column prop="itemName" label="检测项目" show-overflow-tooltip></el-table-column>
                    <el-table-column prop="value" label="检测结果" v-if = "subModel == 'myEntry' || subModel == 'myReviewUpdate'">
                      <template slot-scope="scope">
                        <el-input size="mini" v-model="scope.row.value" ></el-input>
                      </template>
                    </el-table-column>
                    <el-table-column prop="value" label="检测结果" v-if = "subModel != 'myEntry' && subModel != 'myReviewUpdate'"></el-table-column>
                    <el-table-column prop="unitName" label="计量单位"></el-table-column>
                    <!-- <el-table-column prop="unitName" label="计量单位" v-if = "subModel != 'myEntry' && subModel != 'myReviewUpdate'"></el-table-column>
                    <el-table-column prop="unit" label="计量单位" v-if = "subModel == 'myEntry' || subModel == 'myReviewUpdate'">
                        <template slot-scope="scope">
                        <el-select size="mini" v-model="scope.row.unit">
                            <el-option v-for="item in allUnit" :key="item.code" :label="item.ename" :value="item.code">
                            </el-option>
                        </el-select>
                        </template>
                    </el-table-column> -->
                  <el-table-column prop="subcontractorName" label="分包商" show-overflow-tooltip></el-table-column>
                  </el-table>
              </el-tab-pane>
              <el-tab-pane label="流程记录" name="second" v-if = "(subModel == 'myEntry' && subTestpanelData.status == '532') || subModel == 'myCheck' || subModel == 'myReview'">
                 <el-table :data="recordData" style="width: 100%;height:100%;" class="tableCon"  size="mini" highlight-current-row
                 key="recordData">
                  <el-table-column label="序号" width="49px" fixed>
                    <template slot-scope="scope">
                      {{scope.$index+1}}
                    </template>
                  </el-table-column>
                  <el-table-column prop="work" label="流程" min-width="90px">
                  </el-table-column>
                  <el-table-column label="操作时间" prop="createTime" min-width="140px">
                    <template slot-scope="scope">
                      {{scope.row.createTime.split('.')[0]}}
                    </template>
                  </el-table-column>
                  <el-table-column label="操作人" prop="createByName" min-width="90px">
                  </el-table-column>
                  <el-table-column label="意见" prop="opinion" >
                  </el-table-column>
                </el-table>

              </el-tab-pane>
              <el-tab-pane label="附件" name="third">
                  <div style="margin-bottom: 10px;overflow: hidden;">
                    <input type="file" name="file" id="plFile" @change="upload" style="visibility: hidden;width: 0;height: 0;" multiple>
                    <el-button size="mini" type="primary" style="float:right" @click="uploadClick" v-if = "subModel == 'myEntry' || subModel == 'myReviewUpdate'">上传附件</el-button>
                  </div>
                  <el-table :data="renwufujian" style="width: 100%;height:calc(100% - 40px)" class="tableCon" size="mini" highlight-current-row cell-class-name="batchtablecell"
                  key="renwufujian" v-if = "reload">
                    <el-table-column label="序号" width="49px" fixed>
                      <template slot-scope="scopea">
                        {{scopea.$index+1}}
                      </template>
                    </el-table-column>
                    <el-table-column prop="fileName" label="名称" min-width="90px">
                    </el-table-column>
                    <el-table-column label="上传人" prop="createByName" min-width="90px">
                    </el-table-column>
                    <el-table-column label="操作" min-width="90px">
                      <template slot-scope="scope">
                        <el-button type="text" size="small" @click="deleteattachment(scope.row)" v-if="subModel == 'myEntry' || subModel == 'myReviewUpdate'">删除</el-button>
                        <el-button type="text" size="small" @click="dlownloadattachment(scope.row)">下载</el-button>
                        <el-button type="text" size="small" @click="previewFile(scope.row)">预览</el-button>
                      </template>
                    </el-table-column>
                  </el-table>

              </el-tab-pane>
          </el-tabs>


        </div>
      </div>
    </div>
  </div>
  <subcheckDetail :checkShow.sync="checkShow" :subModel = "subModel" :subTestpanelData = "subTestpanelData"></subcheckDetail>

</div>
</template>

<script>
import {
  mapState
} from 'vuex'
const subcheckDetail = () => import('./subcheckDetail.vue');
export default {
  data() {

    return {
      testEntryDetail: [], //数据录入信息
      isRepeat:true,
      allUnit:[],
      receptModuleId:"",
      activeName:"first",
      checkShow:false,
      recordData:[],
      renwufujian:[],
      setIntervalTimes:null,
      isSuccess:true,
      reload:true,

    }
  },
  computed: {
    ...mapState(['testBatchStatus', 'typeQcSelect', 'submitType', 'ruleSelect']),
    sampleTableHeight() {
      return ((window.innerHeight - 310))
    },

  },
  components: {
    subcheckDetail

  },
  props: ['addVisible', 'subTestpanelData','subModel'],
  mounted() {
    this.$store.dispatch('dogetDictionary')

  },
  beforeDestroy(){
    this.isSuccess = true
    clearInterval(this.setIntervalTimes)
  },
  watch: {


    addVisible(val) {
      if (val) {
        // 调用公共函数 传 数据校核 的模块路由取对应的模块id
        if(this.subModel == 'myReviewUpdate'){
          this.receptModuleId = this.util.getModuleId({

            module: "mygroupsanjishenhe"
          })
        }else{
          this.receptModuleId = this.util.getModuleId({

            module: "mygroupcheck"
          })
        }

        this.readAllUnit();
        console.log(this.subTestpanelData)
        this.testEntryDetail = [];
        // 组装检测单信息
          var obj = {};
          obj.code = this.subTestpanelData.code;
          obj.status = this.subTestpanelData.status;
          obj.checkerName = this.subTestpanelData.checkerName;
          obj.togetherWithName = this.subTestpanelData.togetherWithName;
          if(this.subModel != 'myEntry'){
            obj.desc = this.subTestpanelData.desc
          }

          this.testEntryDetail.push(obj)
          if(this.subModel == 'myEntry'){
            var that = this;
            this.setIntervalTimes = setInterval(function () {
              if(that.isSuccess){
                that.resultentry('save', true)
              }

            }, 10000)
          }
        }
    },
    activeName(val){
      if(val == 'second'){
          this.getWorkRecord();
      }else if(val == "third"){
        this.getFilePathByIds();
      }
    }

  },
  methods: {

    //处理状态
    formatterStatus(row, column, cellValue, index) {
      return this.util.changeStatus({
        cellValue: cellValue,
        list: this.testBatchStatus
      })
    },
    // qc类型
    formatterQcType(row, column, cellValue, index) {
      return this.util.codeChangeName({
        cellValue: cellValue,
        list: this.typeQcSelect.itemList
      })
    },
    // 读取单位
    readAllUnit() {
      this.allUnit = [];
      this.$http({
        method: 'post',
        apiUrl: '/technology/readLabUnitList.htm',

      }).then(res => {
        if (res.code == 0) {
          this.allUnit = res.data;
        }
      })
    },
    // 读取用户
    readUser(item) {
      this.$http({
        method: 'post',
        apiUrl: '/resource/readEmployeeByLab.htm',
        params: {
          name: item
        },
        isJson: true,
      }).then(res => {
        if (res.code === 0) {
          this.userData = res.data;

        }

      })
    },
    close(){
      if(this.subModel == 'myEntry'){
        clearInterval(this.setIntervalTimes)
        this.isSuccess = true;
      }

      this.$emit('update:addVisible', false);
      this.isRepeat = true;
      this.activeName = "first";

    },
    // 预览
			previewFile(row){
				var url = "preview/fileToPdfPreview.htm"
        let token = sessionStorage.getItem('loginAccount')?sessionStorage.getItem('loginAccount'):undefined
				window.open(process.env.baseUrl + url + '?id=' + row.id + "&token=" + token);
			},
    getWorkRecord() {
      var data = {
        id: this.subTestpanelData.id
      }
      this.$http({
        method: 'post',
        apiUrl: '/detection/getWorkRecord.htm',
        params: data,
        isJson: false,
      }).then(res => {
        if (res.code === 0) {
          this.recordData = res.data
        }
      })
    },
    // 数据录入提交
    resultentry(val,isTime){
      var msg = "";
      if(val == 'save'){
        this.subTestpanelData.submitType = 0
        msg = "保存成功"

      }else{
        if(this.subModel != 'myReviewUpdate'){
            this.subTestpanelData.moduleId = this.receptModuleId;
            this.subTestpanelData.operation = 'check';
        }

        this.subTestpanelData.submitType = 1;
        msg = "提交成功"
        if(this.subModel == 'myEntry'){
          clearInterval(this.setIntervalTimes)
        }
      }
      // for(var i in this.subTestpanelData.subItems){
      //   for(var j in this.allUnit){
      //     if(this.subTestpanelData.subItems[i].unit == this.allUnit[j].code){
      //       this.subTestpanelData.subItems[i].unitName = this.allUnit[j].ename
      //     }
      //   }
      // }
      this.subTestpanelData.resultBeans = this.subTestpanelData.subItems;
      if(isTime){
        this.isSuccess = false;
      }
      var url = "/detection/addSubResultData.htm"
      if(this.subModel == 'myReviewUpdate'){
        url = "/detection/modSubResultData.htm"
      }
      this.$http({
        method: 'post',
        apiUrl: url,
        params:this.subTestpanelData,
        isJson: true,
      }).then(res => {

        if (res.code == 0) {
          if(!isTime){
             this.$notify({
              message:msg,
              type:"success",
              title:"成功"
            })
            this.close();
            this.$parent.getTestBatchs(this.$parent.testItemQuery)
          }else{
            this.isSuccess = true;
            this.subTestpanelData.commitFlag = 1;
          }

        }
      })
    },
    // 审核
    doPass(){
      this.checkShow = true;
    },
    // 导出模板
    excelTemplet() {
        var url = "detection/subBatchExcelTemplet.htm";
        var id = this.subTestpanelData.id
        let token = sessionStorage.getItem('loginAccount')?sessionStorage.getItem('loginAccount'):undefined
        window.open(process.env.baseUrl + url + '?batch=' + id + "&token=" + token)
    },
     // 导入结果按钮
    uploadClick1() { // 模拟file的点击事件
      document.getElementById("file1").click()
    },
    // 导入文件
    upload1(event) {
      var files = document.getElementById('file1').files[0];
      if (files == undefined) {
        return;
      }
      var formData = new FormData();
      formData.append('file', files)
      this.$axios({
        method: 'post',
        url: '/detection/importBatchData.htm',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data',
          'token':sessionStorage.getItem('loginAccount')?sessionStorage.getItem('loginAccount'):undefined
        }
      }).then(res => {
        this.loading = false;
         event.target.value= "";
        if (res.data.code == 0) {
          this.$notify({
            title: '消息',
            message: '获取数据成功',
            type: 'success'
          })
          this.handleData(res.data.data);

        } else {
          this.$notify({
            title: '消息',
            type: 'warning',
            message: res.data.description,
          })
        }

      })
    },
    handleData(data){
      for(var i in data){
        for(var j in this.subTestpanelData.subItems){
          if(data[i].sampleCode == this.subTestpanelData.subItems[j].sampleCode
          && data[i].itemName == this.subTestpanelData.subItems[j].itemName
          && data[i].methodName == this.subTestpanelData.subItems[j].methodName){
            if(this.subTestpanelData.subItems[j].value == undefined){
               this.$set(this.subTestpanelData.subItems[j],'value',data[i].value)
            }else{
              this.subTestpanelData.subItems[j].value = data[i].value
            }

          }
        }

      }
      console.log(this.subTestpanelData)
      this.reLoad();
    },
    reLoad(){
      this.reload = false;
        this.$nextTick(() => {
          this.reload = true;
        })
    },

   getFilePathByIds() {
      this.$http({
        method: 'post',
        apiUrl: '/download/getFilePathByIds.htm',
        params: { ids: this.subTestpanelData.id },
        isJson: false,
      }).then(res => {
        if (res.code == 0) {
          this.renwufujian = res.data
        }

      })
    },
    uploadClick() {
      document.getElementById('plFile').click()
    },
    upload(event) {
      var files = document.getElementById('plFile').files[0];

      var formData = new FormData();
      // for(var i of files){
        formData.append('file', files)
      // }
      formData.append('ids', this.subTestpanelData.id)
      formData.append('type', 3)
      formData.append('taskType', null)
      formData.append('detectability', null)
      formData.append('fileType', 'batch')
      this.$axios({
        method: 'post',
        url: '/download/fileUpload.htm',
        data: formData,
        headers: {
          'Content-Type': 'multipart/form-data',
          'token':sessionStorage.getItem('loginAccount')?sessionStorage.getItem('loginAccount'):undefined
         }
      }).then(res => {
        var data = res.data
         event.target.value= "";
        if (data.code == 0) {
          this.$notify({
            title: '消息',
            message: '上传成功',
            type: 'success'
          })
          this.getFilePathByIds();
        } else {
          this.$notify({
							title: '消息',
							message: '上传失败',
							type: "warning"
					})
        }

      })
    },
		deleteattachment(row) {
				this.$confirm('是否删除', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(() => {
					this.$http({
						method: 'post',
						apiUrl: '/download/fileDelete.htm',
						params: {
							id: row.id,
						},
						isJson: false,
					}).then(res => {
						if (res.code === 0) {
							this.$message({
								type: 'success',
								message: '删除成功!'
							});
							this.getFilePathByIds();
						}
					})
				}).catch(() => {
					this.$message({
						type: 'info',
						message: '已取消删除'
					});
				});
			},
			// 下载附件
			dlownloadattachment(row) {
				var url = "/download/fileDownload.htm"
        let token = sessionStorage.getItem('loginAccount')?sessionStorage.getItem('loginAccount'):undefined
				window.open(process.env.baseUrl + url + '?id=' + row.id + "&token=" + token);
			},



  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->

<style scoped>

</style><style>
.subeditpanelPop .radioGroup .el-radio {
  margin-left: 30px;
  display: block;
  height: 35px;
  line-height: 35px;
}

.subeditpanelPop .el-input-number.el-input-number--mini {
  width: 100%;
}

.subeditpanelPop .el-input-number.el-input-number--mini input {
  padding: 0 5px;
}
.subeditpanelPop .elTab .el-tabs{
    height:100%;
}
.subeditpanelPop .elTab .el-tabs .el-tabs__content{
   height:calc(100% - 50px);
}
.subeditpanelPop .elTab .el-tabs .el-tabs__content .el-tab-pane{
   height:100%;
}

.resultVoidDialog .el-dialog {
  margin-top: 26vh !important;
}

.resultVoidDialog .el-dialog .el-dialog__header {
  padding: 10px;
  border: none;
}
.resultVoidDialog .el-dialog .el-dialog__body {
  padding: 10px;
}

#file,
#attachmentForm,
#file1 {
  width: 50px;
  height: 20px;
  opacity: 0;
  position: absolute;
  left: 0;
  top: 0;
  z-index: -1;
}
</style>
